package com.zyf.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zyf.springboot.entity.LoginUser;
import com.zyf.springboot.entity.Result;
import com.zyf.springboot.entity.User;
import com.zyf.springboot.mapper.UserMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
public class ListController {
    @Resource
    UserMapper userMapper;
    @PostMapping("/getList")
    public Result<LoginUser> getList(){
        List<User> users = userMapper.selectList(null);
        List<LoginUser> list=new ArrayList<>();
                for (User u:users){
                    LoginUser loginUser = new LoginUser(u.getUsername(),u.getPassword());
                    list.add(loginUser);
                }
        return new Result<>(0,"success",1000,list);
    }
    @GetMapping("/updateUser")
    public Result updateUser(LoginUser loginUser){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("username",loginUser.getUsername());
        User user = new User();
        user.setUsername(loginUser.getUsername());
        user.setPassword(loginUser.getPassword());
        userMapper.update(user,queryWrapper);
        return null;
    }
    @GetMapping("/deleteUser")
    public Result deleteUser(String username){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("username",username);
        userMapper.delete(queryWrapper);
        return null;
    }
    @GetMapping("/selectUser")
    public Result<LoginUser> selectUser(String username){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("username",username);
        List<User> users = userMapper.selectList(queryWrapper);
        List<LoginUser> list=new ArrayList<>();
        for (User u:users){
            LoginUser loginUser = new LoginUser(u.getUsername(),u.getPassword());
            list.add(loginUser);
        }
        return new Result<>(0,"success",1000,list);
    }
    @GetMapping("/addUser")
    public Result<LoginUser> addUser(String username,String password){
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        userMapper.insert(user);
        return null;
    }
}
